<template>
  <div class="indexed-db">
    <el-button type="text" @click="dialogVisible = true">点击打开 Dialog</el-button>
    <el-table
      :data="tableData"
      style="width: 100%">
      <el-table-column
        prop="id"
        label="ID"
        width="80">
      </el-table-column>
      <el-table-column
        prop="name"
        label="姓名"
        width="180">
      </el-table-column>
      <el-table-column
        prop="address"
        label="地址">
      </el-table-column>
      <el-table-column
        prop="phone"
        label="电话"
        width="180">
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="200">
        <template slot-scope="scope">
          <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button>
          <el-button @click="delById(scope.row.id)" type="text" size="small">删除</el-button>
          <el-button type="text" size="small">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- :before-close="handleClose" -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
    >
      <el-form :model="form">
        <el-form-item label="姓名" label-width="100px">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="地址" label-width="100px">
          <el-input v-model="form.address" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" label-width="100px">
          <el-input v-model="form.phone" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addPerson(form)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
 
<script>
export default {
  name: 'IndexedDB',
  data () {
    return {
      db: null,
      personStore: 'person',
      tableData: [],
      dialogVisible: false,
      form: {
        name: '',
        address: '',
        phone: ''
      }
    }
  },
  mounted() {
    let _this = this
    var dbName = 'demoDb', dbVersion = 1;
    // 创建indexedDB对象，兼容各种浏览器
    var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
    if (!indexedDB) {
      console.log("你的浏览器不支持IndexedDB");
    }

    openIndexedDB(this.loadTableData);

    // 打开数据库
    function openIndexedDB(callback) {
      // 打开一个数据库
      var request = indexedDB.open(dbName, dbVersion);

      // 打开失败
      request.onerror = function (e) {
        console.log(e.currentTarget.error.message);
      };

      // 打开成功！
      request.onsuccess = function (e) {
        _this.db = e.target.result;
        console.log('成功打开DB');
        callback();
      };

      // 打开成功后，如果版本有变化自动执行以下事件
      request.onupgradeneeded = function (e) {
        _this.db = e.target.result;
        if (!db.objectStoreNames.contains(_this.personStore)) {
          console.log("我需要创建一个新的存储对象");
          //如果表格不存在，创建一个新的表格（keyPath，主键 ； autoIncrement,是否自增），会返回一个对象（objectStore）
          var objectStore = _this.db.createObjectStore(_this.personStore, {
            keyPath: "id",
            autoIncrement: true
          });

          //指定可以被索引的字段，unique字段是否唯一, 指定索引可以加快搜索效率。
          objectStore.createIndex("name", "name", {
            unique: true
          });
          objectStore.createIndex("phone", "phone", {
            unique: false
          });
        }
        console.log('数据库版本更改为： ' + dbVersion);
      };
    }

  },
  methods: {
    handleClick(row) {
      console.log(row);
    },

    // 配合游标遍历表中数据，并配合art-template生成html
    loadTableData() {
      // document.getElementById('tbd').innerHTML = "";
      var trans = this.db.transaction(this.personStore, 'readwrite');
      var store = trans.objectStore(this.personStore);
      var cursorRequest = store.openCursor();
      cursorRequest.onsuccess = (e) => {
        var cursor = e.target.result;
        console.log(cursor)
        if (cursor) {
          this.tableData.push(cursor.value)
          // var html = template('tbTmpl', cursor.value);
          // document.getElementById('tbd').innerHTML += html;
          cursor.continue(); // 游标继续往下 搜索，重复触发 onsuccess方法，如果到到返回null
        }
      }
    },

    delById(id) {
      if (!this.db || !id) {
        return;
      }
      // 创建一个事务
      var transaction = this.db.transaction(this.personStore, 'readwrite');

      // 通过事务来获取store
      var store = transaction.objectStore(this.personStore);

      // 删除请求
      var delPersonRequest = store.delete(id);
      delPersonRequest.onsuccess = (e) => {
        this.loadTableData(); // 删除成功后，重新加载数据
      }
      delPersonRequest.onerror = function (e) {
        console.log(e.target.error);
      }
    },

    // 添加用户
    addPerson(data) {
      this.dialogVisible = false
      if (!this.db) {
        return;
      }
      // var pName = document.getElementById('name').value;
      // var pPhone = document.getElementById('phone').value;
      // var pAddress = document.getElementById('address').value;
      // 创建一个事务
      var transaction = this.db.transaction(this.personStore, 'readwrite');

      // 通过事务来获取store
      var store = transaction.objectStore(this.personStore);

      let obj = { name: data.name, phone: data.phone, address: data.address }
      var addPersonRequest = store.add(obj);
      addPersonRequest.onsuccess = (e) => {
        console.log(e.target);
        // loadTableData(); // 添加成功后重新加载数据
        this.tableData.push({...obj,id:e.target.result})
      }
      addPersonRequest.onerror = function (e) {
        console.log(e.target.error);
      }
      
    }
  }
}
</script>
 
<style scoped lang="less">
 
</style>